﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using StockholmsStad.Windows.UI.Modules.Maintenance.Models;
using StockholmsStad.Runtime.Serialization.DataContract.Enums;
using StockholmsStad.Windows.UI.Modules.Maintenance.Interfaces;
using StockholmsStad.Runtime.Serialization.DataContract;
using System;
using StockholmsStad.Utilities;

namespace StockholmsStad.Windows.UI.Modules.Maintenance.Controls
{
    /// <summary>
    /// Interaction logic for ParvisUserEditControl.xaml
    /// </summary>
    public partial class ParvisUserDetailsControl
    {
        private readonly IUserService userService;
        private List<UserRole> roles;
        private UserPresentationModel model;

        public ParvisUserDetailsControl(IUserService service)
        {
            userService = service;

            Initialized += ParvisUserDetailsControl_Initialized;
            InitializeComponent();

            DataContextChanged += ParvisUserDetailsControl_DataContextChanged;
            KeyUp += UserControl_KeyUp;
        }

        public UserPresentationModel Model
        {
            get { return DataContext as UserPresentationModel; }
            set { DataContext = value; }
        }

        private void ParvisUserDetailsControl_Initialized(object sender, EventArgs e)
        {
            try
            {
                roles = userService.GetRoles();
                ComboBoxUserRole.ItemsSource = roles;
            }
            catch (Exception)
            {
            }      
        }

        private void ParvisUserDetailsControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            model = DataContext as UserPresentationModel;

            if (model != null)
            {
                if (model.UserRole != null)
                {
                    ComboBoxUserRole.SelectedIndex = FindSelectedIndex(model.UserRole.Name);
                }
                else
                {
                    // Ny användare
                    model.UserRole = new ValueIdPair {Name = Enum.GetName(typeof (UserRole), roles[0]), Id = 3};
                    ComboBoxUserRole.SelectedIndex = FindSelectedIndex(model.UserRole.Name);
                }
            }
        }

        private int FindSelectedIndex(string name)
        {
            if (ComboBoxUserRole.Items == null)
                return -1;

            for (int i = 0; i < ComboBoxUserRole.Items.Count; i++)
            {
                var item = (UserRole) ComboBoxUserRole.Items[i];

                if(Enum.GetName(typeof(UserRole), item) == name)
                    return i;
            }

            return -1;
        }

        private void UserControl_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            ToggleButtons();
            TogglePasswordAndDeleteButton();
            e.Handled = true;
        }

        private void ToggleButtons()
        {
            if (model != null)
            {
                bool enabled = false;

                enabled = !TextBoxFirstName.Text.Equals(model.FirstName) || enabled;
                enabled = !TextBoxLastName.Text.Equals(model.LastName) || enabled;
                enabled = !TextBoxUserName.Text.Equals(model.EmailAddress) || enabled;
                enabled = !TextBoxPhoneNumber.Text.Equals(model.PhoneNumber) || enabled;
                enabled = !TextBoxCellPhone.Text.Equals(model.CellPhoneNumber) || enabled;

                // Comboboxen
                if (ComboBoxUserRole.SelectedItem != model.UserRole)
                    enabled = true;

                if (enabled && !CanSave())
                {
                    SaveButton.Visibility = Visibility.Collapsed;
                    CancelButton.Visibility = Visibility.Collapsed;
                }
                else
                {
                    SaveButton.Visibility = enabled ? Visibility.Visible : Visibility.Collapsed;
                    CancelButton.Visibility = enabled ? Visibility.Visible : Visibility.Collapsed;
                }
            }
        }

        private void TogglePasswordAndDeleteButton()
        {
            bool enabled = false;

            enabled = model.FirstName != string.Empty || enabled;
            enabled = model.LastName != string.Empty || enabled;
            enabled = model.EmailAddress != string.Empty || enabled;
            enabled = model.PhoneNumber != string.Empty || enabled;
            enabled = model.CellPhoneNumber != string.Empty || enabled;
            enabled = model.UserRole != null || enabled;

            ChangePasswordButton.Visibility = enabled ? Visibility.Visible : Visibility.Collapsed;
            DeleteButton.Visibility = enabled ? Visibility.Visible : Visibility.Collapsed;
        }

        private bool CanSave()
        {
            // This is an ugly fix since this class does not want to listen to ParvisUserAddedEvent for some reason
            if (TextBoxFirstName.Text == string.Empty || TextBoxLastName.Text == string.Empty || TextBoxPhoneNumber.Text == string.Empty
                || TextBoxUserName.Text == string.Empty || ComboBoxUserRole.SelectedItem == null)
            {
                return false;
            }

            return true;
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            if (CanSave())
            {
                // This is an ugly fix since this class does not want to listen to ParvisUserAddedEvent for some reason
                if (model.EmailAddress != null && !model.EmailAddress.Equals(TextBoxUserName.Text))
                {
                    MessageBoxResult result = MessageBox.Show(
                        "Är du säker på att du vill byta användarnamn (inloggningsnamnet kommer då att ändras)?",
                        "Information", MessageBoxButton.YesNo, MessageBoxImage.Information);

                    if (result == MessageBoxResult.No)
                    {
                        TextBoxUserName.Text = model.EmailAddress;
                        ToggleButtons();
                        return;
                    }
                }

                BindingExpression be = TextBoxFirstName.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                be = TextBoxLastName.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                be = TextBoxUserName.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                be = TextBoxPhoneNumber.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                be = TextBoxCellPhone.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                var selectedItem = (UserRole) ComboBoxUserRole.SelectedItem;
                model.UserRole = new ValueIdPair
                                     {
                                         Name = Enum.GetName(typeof (UserRole), selectedItem),
                                         Id = (int) selectedItem,
                                         Description = EnumUtility.GetEnumDescription(selectedItem)
                                     };

                model.SaveCommand.Execute(model);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            TextBoxFirstName.Text = model.FirstName;
            TextBoxLastName.Text = model.LastName;
            TextBoxUserName.Text = model.EmailAddress;
            TextBoxPhoneNumber.Text = model.PhoneNumber;
            TextBoxCellPhone.Text = model.CellPhoneNumber;

            if (model.UserRole != null)
                ComboBoxUserRole.SelectedIndex = FindSelectedIndex(model.UserRole.Name);
            else
                ComboBoxUserRole.SelectedIndex = -1;

            ToggleButtons();
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show(
                "Är du säker på att du vill ta bort användaren?",
                "Information", MessageBoxButton.YesNo, MessageBoxImage.Information);

            if (result == MessageBoxResult.Yes)
                model.DeleteCommand.Execute(model);

            ToggleButtons();
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            // This is an ugly fix since this class does not want to listen to ParvisUserAddedEvent for some reason
            Model = userService.AddNewUser();
        }
    }
}
